const Router = require('koa-router')
const fs = require("fs")
const { ossConfig } = require("../../config/index")
const path = require("path")
const OSS = require('ali-oss');
const { tokenIsValid, Success, refreshTokenIsValid, generateToken, generateRefreshToken, setCookie } = require('../../core/common')
const router = new Router({
  prefix: '/v1/common'
})

const client = new OSS(ossConfig);


router.post('/vertifyToken', async (ctx) => {
  const { token } = ctx.request.body
  const isValid = tokenIsValid(token)
  if (isValid) {
    Success(ctx)
  }
})
//刷新access_token
router.post('/refreshToken', async (ctx) => {
  const { refresh_token } = ctx.request.body
  const decode = refreshTokenIsValid(refresh_token)
  if (decode) {
    const token = generateToken(decode.uid)
    const refreshToken = generateRefreshToken(decode.uid)
    // setCookie未知原因失败
    // setCookie(ctx, "access_token", token)
    // setCookie(ctx, "refresh_token", refreshToken)
    Success(ctx, { token, refreshToken })
  }
})

// 图片上传
router.post("/upload", async ctx => {
  // 上传单个文件
  const file = ctx.request.files.file; // 获取上传文件
  // // 创建可读流
  // const reader = fs.createReadStream(file.path);
  // let filePath = path.resolve(__dirname,'../../../static/upload'+`/${file.name}`);
  // const outPath=`/upload/${file.name}`
  // // 创建可写流
  // const upStream = fs.createWriteStream(filePath);
  // // 可读流通过管道写入可写流
  // reader.pipe(upStream);
  // Success(ctx, {url:outPath})


  // use 'chunked encoding'
  let stream = fs.createReadStream(file.path);
  let result = await client.putStream(file.name, stream);
  Success(ctx, { url: result.url })

})
module.exports = router
